package com.sk.leetcode.arithmetic;

import com.alibaba.fastjson.JSON;

/**
 * 给定一个正整数 n，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的正方形矩阵。
 * 输入: 3
 * 输出:
 * [
 * [ 1, 2, 3 ],
 * [ 8, 9, 4 ],
 * [ 7, 6, 5 ]
 * ]
 */
public class Test59 {
    public static void main(String[] args) {
        int[][] res = generateMatrix(1);
        System.out.println(JSON.toJSONString(res));
    }

    public static int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int width = res.length - 1, widthF = 0;
        int length = res[0].length - 1, lengthF = 0;
        boolean left = true, down = false, right = false, up = false;
        int a = 0, b = 0;
        int num = 0;
        while (true) {
            res[b][a] = ++num;
            if(left) {
                if(a < length) {
                    a++;
                } else {
                    if(b < width) {
                        b++;
                        left = false;
                        down = true;
                        widthF++;
                    } else {
                        return res;
                    }
                }
            } else if(down) {
                if(b < width) {
                    b++;
                } else {
                    if(a > lengthF) {
                        a--;
                        down = false;
                        right = true;
                        length--;
                    } else {
                        return res;
                    }
                }
            } else if(right) {
                if(a > lengthF) {
                    a--;
                } else {
                    if(b > widthF) {
                        b--;
                        right = false;
                        up = true;
                        width--;
                    } else {
                        return res;
                    }
                }
            } else if(up) {
                if(b > widthF) {
                    b--;
                } else {
                    if(a < length) {
                        a++;
                        up = false;
                        left = true;
                        lengthF++;
                    } else {
                        return res;
                    }
                }
            }
        }


    }
}
